package com.liqi.quartz.task;

import com.alibaba.fastjson.JSON;

import com.liqi.system.domain.SysMail;
import com.liqi.system.service.IMailService;
import com.liqi.system.service.ISysMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component("mailTask")
public class MailTask{
    @Autowired
    private ISysMailService SysMailService;
    @Autowired
    private IMailService mailService;

    public void SendMail() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("2022定时器被触发" + sdf.format(new Date()));
        List<SysMail> sysMails = SysMailService.selectSysMailBySendFlag(0);
        if(sysMails==null){
            System.out.println("暂无需要发送的邮件");
        }
        for (int i = 0; i <sysMails.size() ; i++) {
            try {

                HashMap map = JSON.parseObject(sysMails.get(i).getBody(), HashMap.class);
                if(map.get("reportType").equals("人工上报")){
                sysMails.get(i).setAttachment(map);

                mailService.sendTemplateMailByLabor(sysMails.get(i));

                sysMails.get(i).setSendFlag("3");
                sysMails.get(i).setSendTime(new java.sql.Date(new java.util.Date().getTime()));
                sysMails.get(i).setSendInfo("");
                SysMailService.updateSysMail(sysMails.get(i));

                }
                else if(map.get("reportType").equals("运行中上报")||map.get("reportType").equals("设备自检上报")||map.get("reportType").equals("心跳上报")) {
                    sysMails.get(i).setAttachment(map);

                    mailService.sendTemplateMailByDevice(sysMails.get(i));

                    sysMails.get(i).setSendFlag("3");
                    sysMails.get(i).setSendTime(new java.sql.Date(new java.util.Date().getTime()));
                    sysMails.get(i).setSendInfo("");
                    sysMails.get(i).setUpdateBy("邮箱发送定时任务成功");
                    SysMailService.updateSysMail(sysMails.get(i));}
                else {
                    System.out.println("暂无需要发送的邮件");
                }
            }

            catch (Exception e) {
                e.printStackTrace();
            sysMails.get(i).setSendInfo(e.getMessage());
            sysMails.get(i).setSendFlag("6");
                sysMails.get(i).setUpdateBy("邮箱发送定时任务失败");
            SysMailService.updateSysMail(sysMails.get(i));
            }
        }

    }
}
